<template>
    <section style="padding: 24px; background:#fff;">
        <a-form>
            <a-form-item
                label="标题"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <div class="article-post-box">
                    <!-- 标题 -->
                    <div class="article-title-part">
                        <a-input
                            placeholder="文章标题（8-64个字符）"
                            :maxLength="64"
                            allowClear
                            v-model="article.title"
                        ></a-input>
                    </div>
                </div>
            </a-form-item>
            <a-form-item label="内容" :label-col="labelCol">
                <mavon-editor
                    ref="md"
                    defaultOpen="preview"
                    v-model="article.content"
                    placeholder="请输入文档内容..."
                    :boxShadow="false"
                    @htmlCode="htmlCode"
                    style="z-index:1;border: 1px solid #d9d9d9;height:800px"
                    codeStyle="atom-one-light"
                    toolbarsBackground="#e9e7ef"
                    :toolbars="toolbars"
                    @imgAdd="handleEditorImgAdd"
                    @imgDel="handleEditorImgDel"
                >
                </mavon-editor>
            </a-form-item>
            <a-form-item
                label="分类"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-select
                    placeholder="文章分类"
                    style="width: 400px"
                    option-filter-prop="children"
                    v-model="article.categoryId"
                >
                    <a-select-option
                        v-for="item in categoryList"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.name }}</a-select-option
                    >
                </a-select>
            </a-form-item>
            <a-form-item
                label="摘要"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-textarea
                    placeholder="请您输入摘要!"
                    v-model="article.summary"
                    :rows="4"
                />
            </a-form-item>
            <a-form-item
                label="封面"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-upload
                    name="cover"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :customRequest="selfUpload"
                    :before-upload="beforeUpload"
                    @change="handleChange"
                >
                    <img
                        v-if="article.cover"
                        :src="article.cover"
                        alt="cover"
                        width="250"
                        height="150"
                    />
                    <div v-else>
                        <a-icon :type="imgloading ? 'loading' : 'plus'" />
                        <div class="ant-upload-text">
                            Upload
                        </div>
                    </div>
                </a-upload>
            </a-form-item>
            <a-form-item
                label="类型"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-select
                    default-value="1"
                    style="width: 200px"
                    @change="handleWriteTypeChange"
                    v-model="article.writeType"
                >
                    <a-select-option value="1">
                        原创
                    </a-select-option>
                    <a-select-option value="2">
                        转载
                    </a-select-option>
                    <a-select-option value="3">
                        衍生
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="来源"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                v-if="article.writeType==2"
            >
                <div class="article-post-box">
                    <!-- 标题 -->
                    <div class="article-title-part">
                        <a-input
                            placeholder="请输入转载地址!"
                            allowClear
                            v-model="article.reprintSource"
                        ></a-input>
                    </div>
                </div>
            </a-form-item>
            <a-form-item label="标签" :label-col="labelCol">
                <div>
                    <template v-for="(tag, index) in tags">
                        <a-tooltip
                            v-if="tag.length > 5"
                            :key="tag"
                            :title="tag"
                        >
                            <a-tag
                                :key="tag"
                                :closable="index !== 0"
                                @close="() => handleClose(tag)"
                                color="#2db7f5"
                            >
                                {{ `${tag.slice(0, 5)}...` }}
                            </a-tag>
                        </a-tooltip>
                        <a-tag
                            v-else
                            :key="tag"
                            :closable="true"
                            @close="() => handleClose(tag)"
                            color="#2db7f5"
                        >
                            {{ tag }}
                        </a-tag>
                    </template>
                    <a-input
                        v-if="inputVisible"
                        ref="input"
                        type="text"
                        size="small"
                        :style="{ width: '78px' }"
                        :value="inputValue"
                        @change="handleInputChange"
                        @blur="handleInputConfirm"
                        @keyup.enter="handleInputConfirm"
                    />
                    <a-tag
                        v-else-if="tags.length < 5"
                        style="background: #fff; borderStyle: dashed;"
                        @click="showInput"
                    >
                        <a-icon type="plus" /> New Tag
                    </a-tag>
                </div>
            </a-form-item>

            <a-form-item>
                <div style=" text-align: center;">
                    <a-space>
                        <a-button key="submit" type="primary" @click="preView"
                            >全屏预览</a-button
                        >
                        <a-button
                            type="primary"
                            @click="saveArticleDraft"
                            v-if="!disableDraftBtn"
                            >保存草稿</a-button
                        >
                        <a-button
                            type="primary"
                            @click="saveArticleDraft"
                            v-else
                            disabled
                            >保存草稿</a-button
                        >
                        <a-button type="primary" @click="commitArticle">{{
                            commitText
                        }}</a-button>
                    </a-space>
                </div>
            </a-form-item>
        </a-form>
        <div>
            <a-modal v-model="saveConfirmDialogShow" title="您确定要离开?">
                <template slot="footer">
                    <a-button key="back" @click="saveConfirmDialogShow = false">
                        取消
                    </a-button>
                    <a-button key="submit" type="primary" @click="toNextPath">
                        确定
                    </a-button>
                </template>
                <span>系统可能不会保存你的稿件信息呀</span>
            </a-modal>
        </div>
    </section>
</template>
<script>
import {
    imgUpload,
    listCategories,
    postArticle,
    updateArticle,
    saveArticleDraft,
    getArticleDetail,
} from "@/api/api";
export default {
    data() {
        return {
            labelCol: { span: 1 },
            saveConfirmDialogShow: false,
            wrapperCol: { span: 20 },
            loading: false,
            imgloading: false,
            article: {
                id: "",
                title: "",
                content: "",
                categoryId: "",
                summary: "",
                cover: "",
                labels: "",
                statue: "1",
                writeType:"1",
                reprintSource:'',
                type: "1",
                createTime: null,
            },
            categoryList: [],
            //富文本控件
            toolbars: {
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                help: true, // 帮助
                undo: true, // 上一步
                redo: true, // 下一步
                trash: true, // 清空
                save: false, // 保存（触发events中的save事件）
                navigation: true, // 导航目录
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                subfield: true, // 单双栏模式
                preview: true, // 预览
            },
            //标签
            tags: [],
            inputVisible: false,
            inputValue: "",
            commitText: "发表文章",
            disableDraftBtn: false,
            isContentSave: false,
            nextPath: "",
            hasContentChange: false,
        };
    },
    methods: {
        toNextPath() {
            this.hasContentChange = true;
            this.saveConfirmDialogShow = true;
            this.isContentSave = true;
            this.$router.push({
                path: this.nextPath,
            });
        },
        //标签删除
        handleClose(removedTag) {
            const tags = this.tags.filter((tag) => tag !== removedTag);
            this.tags = tags;
        },
        //显示标签输入框
        showInput() {
            this.inputVisible = true;
            this.$nextTick(function() {
                this.$refs.input.focus();
            });
        },
        handleInputChange(e) {
            this.inputValue = e.target.value;
        },
        //输入框回车事件
        handleInputConfirm() {
            const inputValue = this.inputValue;
            let tags = this.tags;
            if (inputValue && tags.indexOf(inputValue) === -1) {
                tags = [...tags, inputValue];
            }
            console.log(tags);
            Object.assign(this, {
                tags,
                inputVisible: false,
                inputValue: "",
            });
        },
        //全屏预览
        preView() {
            this.$refs.md.toolbar_right_click("read");
        },
        //保存草稿
        saveArticleDraft() {
            if (this.article.title === "") {
                this.$message.error("文章标题不可以为空");
                return;
            }
            if (this.article.content === "") {
                this.$message.error("内容不可以为空");
                return;
            }
            if (this.article.categoryId === "") {
                this.$message.error("请您选择分类!");
                return;
            }
            if (this.article.summary === "") {
                this.$message.error("摘要不可以为空");
                return;
            }
            if (this.article.cover === "") {
                this.$message.error("请设置文章封面");
                return;
            }
            if (this.tags.length === 0) {
                this.$message.error("请设置标签，方便检索分类");
                return;
            }
            let tempLabels = "";
            //处理标签
            this.tags.forEach((item, index) => {
                tempLabels += item;
                if (index !== this.tags.length - 1) {
                    tempLabels += ",";
                }
            });
            this.article.labels = tempLabels;
            this.article.statue = "2";
            saveArticleDraft(this.article).then((result) => {
                if (result.code === 200) {
                    // window.onbeforeunload = null;
                    this.isContentSave = true;
                    this.$message.success(result.message);
                    //跳转到文章列表界面
                    this.$router.push({
                        path: "/content/manage-article",
                    });
                } else {
                    this.$message.error(result.message);
                }
            });
        },
        //发表文章
        commitArticle() {
            if (this.article.title === "") {
                this.$message.error("文章标题不可以为空");
                return;
            }
            if (this.article.content === "") {
                this.$message.error("内容不可以为空");
                return;
            }
            if (this.article.categoryId === "") {
                this.$message.error("请您选择分类!");
                return;
            }
            if (this.article.summary === "") {
                this.$message.error("摘要不可以为空");
                return;
            }
            if (this.article.cover === "") {
                this.$message.error("请设置文章封面");
                return;
            }
             if (this.article.writeType === "") {
                this.$message.error("请设置文章类型");
                return;
            }
            if (this.tags.length === 0) {
                this.$message.error("请设置标签，方便检索分类");
                return;
            }
            let tempLabels = "";
            //处理标签
            this.tags.forEach((item, index) => {
                tempLabels += item;
                if (index !== this.tags.length - 1) {
                    tempLabels += ",";
                }
            });
            this.article.labels = tempLabels;
            // const params = Object.assign(this.article, {})
            //判断一下是更新文章还是保存文章
            if (this.article.id == "") {
                postArticle(this.article).then((result) => {
                    if (result.code === 200) {
                        // window.onbeforeunload = null;
                        this.isContentSave = true;
                        this.$message.success(result.message);
                        //跳转到文章列表界面
                        this.$router.push({
                            path: "/content/manage-article",
                        });
                    } else {
                        this.$message.error(result.message);
                    }
                });
            } else {
                //更新文章
                if (this.article.state === "0" || this.article.state === "2") {
                    this.article.state = "1";
                }
                updateArticle(this.article.id, this.article).then((result) => {
                    if (result.code === 200) {
                        // window.onbeforeunload = null;
                        this.isContentSave = true;
                        this.$message.success(result.message);
                        //跳转到文章列表界面
                        this.$router.push({
                            path: "/content/manage-article",
                        });
                    } else {
                        this.$message.error(result.message);
                    }
                });
            }
        },
        //上传事件监听
        handleChange(info) {
            if (info.file.status === "uploading") {
                this.imgloading = true;
                return;
            }
            if (info.file.status === "done") {
                this.imgloading = false;
            }
        },
        selfUpload(data) {
            const formData = new FormData();
            formData.append("file", data.file);
            imgUpload(formData, "article").then((res) => {
                if (res.code === 200) {
                    this.article.cover = res.data;
                }
            });
        },
        beforeUpload(file) {
            const isJpgOrPng =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/jpg" ||
                file.type === "image/gif";
            if (!isJpgOrPng) {
                this.$message.error("您只能上传图片!");
            }
            const isLt2M = file.size / 1024 / 1024 < 50;
            if (!isLt2M) {
                this.$message.error("图片不能大于1M");
            }
            return isJpgOrPng && isLt2M;
        },
        //富文本编辑器文件上传
        handleEditorImgAdd(pos, $file) {
            //上传
            //TODO 多图片上传
            let file = $file;
            var formdata = new FormData();
            formdata.append("file", $file);
            imgUpload(formdata, "article").then((res) => {
                if (res.code === 200) {
                    let imgUrl = res.data;
                    this.$refs.md.$img2Url(pos, imgUrl);
                }
            });
        },
        //富文本编辑器图片删除
        handleEditorImgDel() {},
        htmlCode(status, value) {},
        //获取分类列表
        getCatrgoryList(pageNo, pageSize) {
            listCategories(pageNo, pageSize).then((res) => {
                if (res.code === 200) {
                    this.categoryList = res.data.records;
                }
            });
        },
        getArticleDetail(articleId) {
            getArticleDetail(articleId).then((result) => {
                if (result.code === 200) {
                    let remoteArticle = result.data;
                    this.article.id = remoteArticle.id;
                    this.article.title = remoteArticle.title;
                    this.article.content = remoteArticle.content;
                    this.article.categoryId = remoteArticle.categoryId;
                    this.article.summary = remoteArticle.summary;
                    this.article.cover = remoteArticle.cover;
                    this.article.writeType=remoteArticle.writeType;
                    this.article.reprintSource=remoteArticle.reprintSource;
                    let labels = remoteArticle.labels;
                    this.tags = labels.split(",");
                    this.article.statue = remoteArticle.statue;
                    this.article.type = remoteArticle.type;
                    //如果当前文章的状态是草稿按钮显示发表文章
                    //如果已经发布的，按钮显示更新（发表、删除、置顶）
                    if (this.article.state === "2") {
                        this.commitText = "发布文章";
                        this.disableDraftBtn = false;
                    } else {
                        this.commitText = "更新文章";
                        this.disableDraftBtn = true;
                    }
                }
            });
        },
    },
    mounted() {
        // window.onbeforeunload = function () {
        //     return '系统可能不会保存填写的文章信息哦';
        // };
        //是否要获取文章详情
        let articleId = this.$route.query.articleId;
        if (articleId) {
            this.getArticleDetail(articleId);
        }
        this.getCatrgoryList(1, 100);
    },
    beforeRouteLeave(to, from, next) {
        if (this.isContentSave || !this.hasContentChange) {
            next();
        } else {
            this.nextPath = to.path;
            this.saveConfirmDialogShow = true;
        }
    },
    watch: {
        article: {
            handler() {
                this.hasContentChange = true;
            },
            deep: true,
        },
    },
};
</script>
<style scoped>
.article-title-part {
    border: none;
    font-size: 20px;
    width: 400px;
}
.article-post-part {
    border: none;
    height: 800px;
    box-shadow: none !important;
}
.margin-bottom-20 {
    margin-bottom: 20px;
}
</style>
